package com.itmuch.contentcenter.controller.content;

import com.itmuch.contentcenter.domain.dto.content.ShareAuditDTO;
import com.itmuch.contentcenter.domain.entity.content.Share;
import com.itmuch.contentcenter.service.content.ShareSeataService;
import com.itmuch.contentcenter.service.content.ShareService;
import com.itmuch.contentcenter.tcc.action.ResultHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShareAdminController {
    private final ShareService shareService;

    @PutMapping("/admin/shares/audit/{id}")
    public Share auditById(@PathVariable Integer id, @RequestBody ShareAuditDTO auditDTO) {
        return this.shareService.auditById(id, auditDTO);
    }

    private final ShareSeataService shareSeataService;

    @PutMapping("/admin/shares/audit/seata1/{id}")
    public Share auditByIdSeata1(@PathVariable Integer id, @RequestBody ShareAuditDTO auditDTO) {
        return this.shareSeataService.auditById(id, auditDTO);
    }

    @GetMapping("tcc-commit")
    public String tccTransactionCommit() {
        Map<String, String> map = new HashMap<>();
        this.shareSeataService.tccTransactionCommit(map);
        String xid = map.get("xid");
        // 结果T
        return ResultHolder.getActionOneResult(xid)+ResultHolder.getActionTwoResult(xid);
    }

    @GetMapping("/tcc-rollback")
    public String tccTransactionRollback() {
        Map<String, String> map = new HashMap<>();
        try {
            this.shareSeataService.tccTransactionRollback(map);
        } catch (Throwable t) {
            log.warn("事务回滚..", t);
        }
        String xid = map.get("xid");
        // 结果R
        return ResultHolder.getActionOneResult(xid) + ResultHolder.getActionTwoResult(xid);
    }
}
